################################################################################
# The MIT License (MIT)
#
# Copyright (c) 2014 Kevin Haroldsen
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
################################################################################

from .util import guid_bracket
from .objects import object_info, object_info_str, knownguids
from .bcdelement import BCDElement


class BCDObject:

    def __init__(self, bcd, guid):
        self.rootnode = -1
        self.bcd = bcd
        self.title = None
        self._elements = None
        self.changed = False
        self._guid = guid_bracket(guid)
        self._nav = self.bcd._nav.get('/Objects/' + self._guid)
        self._type = self._nav.value('Type', path='Description')
        self._type_info = object_info(self._type)
        self.apptype = self._type_info[2]

        if self._guid in knownguids:
            self.title = knownguids[self._guid][1]
        else:
            self.title = object_info_str(self._type)

        self.changed = False

    def __str__(self):
        return 'BCDObject%s' % self.identifier

    def __repr__(self):
        return str(self)

    def __hash__(self):
        return hash(frozenset((hash(e) for e in self.elements)))

    def __iter__(self):
        return iter(self.elements)

    def __getitem__(self, identifier):
        for e in self.elements:
            if e.identifier == identifier or e._type == identifier:
                return e.value
        else:
            raise KeyError('Element "%s" not found' % identifier)

    def __contains__(self, identifier):
        try:
            self[identifier]
            return True
        except KeyError:
            return False

    def __setitem__(self, identifier, value):
        for e in self.elements:
            if e.identifier == identifier or e._type == identifier:
                pass

    def __getattr__(self, identifier):
        try:
            return self[identifier]
        except KeyError:
            raise AttributeError('Element "%s" not found' % identifier)

    def _generate_elements(self):
        self._elements = tuple((BCDElement(self, entry) for entry in self._nav.subkeys('Elements')))

    @property
    def guid(self):
        return self._guid

    @property
    def identifier(self):
        try:
            return self.bcd.guid_to_known(self.guid)
        except Exception:
            # Let the exception propagate for the library user to handle
            raise

    @property
    def elements(self):
        if self._elements is None:
            self._generate_elements()
        return self._elements
